﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
/*编写一个订单管理的控制台程序，实现添加订单、删除订单、修改订单、查询订单（按照订单号、商品名称、客户、订单金额等进行查询）功能。
提示：主要的类有Order（订单）、OrderDetails（订单明细），OrderService（订单服务），
订单数据可以保存在OrderService中一个List中。在Program里面可以调用OrderService的方法完成各种订单操作。
要求：
（1）使用LINQ实现各种查询功能，查询结果按照订单总金额排序返回。
（2）在订单删除、修改失败时，能够产生异常并显示给客户错误信息。
（3）作业的订单和订单明细类需要重写Equals方法，确保添加的订单不重复，每个订单的订单明细不重复。
（4）订单、订单明细、客户、货物等类添加ToString方法，用来显示订单信息。
（5）OrderService提供排序方法对保存的订单进行排序。默认按照订单号排序，也可以使用Lambda表达式进行自定义排序。
*/
// 订单明细类
class OrderDetails : IEquatable<OrderDetails>
{
    public string ProductName { get; set; }//商品名称
    public double Price { get; set; }//单价
    public int Quantity { get; set; }//数量

    public OrderDetails(string productName, double price, int quantity)
    {
        ProductName = productName;
        Price = price;
        Quantity = quantity;
    }

    // 重写Equals方法，确保每个订单明细不重复
    public bool Equals(OrderDetails obj)
    {
        if (obj == null)
            return false;
        return this.ProductName == obj.ProductName &&
             this.Price == obj.Price &&
            this.Quantity == obj.Quantity;
    }

    // 重写ToString方法，用于显示订单明细信息
    public override string ToString()
    {
        return $"商品名称: {ProductName}, 单价: {Price}, 数量: {Quantity}";
    }
}

// 订单类
class Order : IEquatable<Order>
{
    public int OrderId { get; set; }//订单号
    public string Customer { get; set; }//客户
    public List<OrderDetails> Details { get; set; }//订单明细
    public double TotalPrice { get => Details.Sum(d => d.Price * d.Quantity); }//总价lambda表达式实现

    public Order(int orderId, string customer, List<OrderDetails> details)
    {
        OrderId = orderId;
        Customer = customer;
        Details = details;
    }

    // 重写Equals方法，确保每个订单不重复
    public bool Equals(Order other)
    {
        if (other == null)
            return false;
        return this.OrderId == other.OrderId;
    }

    // 重写ToString方法，用于显示订单信息
    public override string ToString()
    {
        return $"订单号: {OrderId}, 客户: {Customer}, 总价: {TotalPrice}";
    }
}

// 订单服务类
class OrderService
{
    private List<Order> orders = new List<Order>();

    // 添加订单
    public void AddOrder(Order order)
    {
        if (orders.Contains(order))
            throw new Exception("订单重复！");
        orders.Add(order);
    }

    // 删除订单
    public void RemoveOrder(int orderId)
    {
        var order = GetOrderById(orderId);
        if (order == null)
            throw new Exception($"未找到{orderId}该订单！");
        orders.Remove(order);
    }

    // 修改订单
    public void UpdateOrder(Order newOrder)
    {
        var oldOrder = GetOrderById(newOrder.OrderId);
        if (oldOrder == null)
            throw new Exception($"未找到{newOrder.OrderId}该订单！");
        orders.Remove(oldOrder);
        orders.Add(newOrder);
    }

    // 按照订单号查询订单
    public Order GetOrderById(int orderId)
    {
        return orders.Where(o => o.OrderId == orderId).FirstOrDefault();
    }

    // 按照商品名称查询订单
    public List<Order> QueryByProductName(string productName)
    {
        return orders.Where(o => o.Details.Any(d => d.ProductName == productName)).ToList();
    }

    // 按照客户查询订单
    public List<Order> QueryByCustomer(string customer)
    {
        return orders.Where(o => o.Customer == customer).ToList();
    }
    // 按照订单金额查询订单
    public List<Order> QueryByTotalPrice(double totalPrice)
    {
        return orders.Where(o => o.TotalPrice == totalPrice).ToList();
    }

    // 按照客户和订单金额范围查询订单
    public List<Order> QueryByCustomerAndPriceRange(string customer, double minPrice, double maxPrice)
    {
        return orders.Where(o => o.Customer == customer && o.TotalPrice >= minPrice && o.TotalPrice <= maxPrice).ToList();
    }

    // 排序方法，默认按照订单号排序
    public void SortOrders()
    {
        orders.Sort((o1, o2) => o1.OrderId.CompareTo(o2.OrderId));
    }

    // 自定义排序方法
    public void SortOrders(Comparison<Order> comparison)
    {
        orders.Sort(comparison);
    }
    // 导出订单
    public void Export(string fileName)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (TextWriter writer = new StreamWriter(fileName))
        {
            serializer.Serialize(writer, orders);
        }
    }

    // 导入订单
    public void Import(string fileName)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (TextReader reader = new StreamReader(fileName))
        {
            List<Order> importedOrders = (List<Order>)serializer.Deserialize(reader);
            orders.AddRange(importedOrders);
        }
    }
}

// 控制台程序类
class Program
{
    static void Main(string[] args)
    {
        OrderService service = new OrderService();
        // 添加订单
        List<OrderDetails> details1 = new List<OrderDetails>() { new OrderDetails("Product1", 100, 2), new OrderDetails("Product2", 50, 3) };
        Order order1 = new Order(1, "Customer1", details1);
        service.AddOrder(order1);

        List<OrderDetails> details2 = new List<OrderDetails>() { new OrderDetails("Product3", 80, 1), new OrderDetails("Product4", 20, 4) };
        Order order2 = new Order(2, "Customer2", details2);
        service.AddOrder(order2);

        // 查询订单
        var result = service.QueryByCustomerAndPriceRange("Customer2", 0, 200);
        foreach (var order in result)
        {
            Console.WriteLine(order);
            foreach (var detail in order.Details)
            {
                Console.WriteLine(detail);
            }
        }

        // 排序订单
        service.SortOrders((o1, o2) => o2.TotalPrice.CompareTo(o1.TotalPrice));

        // 删除订单
        service.RemoveOrder(1);

        // 修改订单
        order2.Details[0].Quantity = 2;
        service.UpdateOrder(order2);
    }
}